<template>
  <div class="w-screen h-screen bg-gray-50 relative overflow-hidden">
    <!-- 顶部语言和下载按钮 -->
    <div class="absolute top-5 right-5 flex gap-4 items-center z-10">
      <LanguageSelector v-model:currentLanguage="currentLanguage" @update:currentLanguage="setLanguage" />

      <el-popover placement="bottom" trigger="click" popper-class="download-popover">
        <template #reference>
          <el-button size="small">{{ messages.downloadApp }}</el-button>
        </template>
        <div class="flex flex-col gap-2">
          <div class="flex items-center py-2 gap-2">
            <div class="w-7 h-7 flex items-center justify-center text-xl">
              <IOS class="text-[#000] text-2xl" />
            </div>
            <div class="flex flex-col">
              <h3 class="m-0 text-sm">{{ messages.appStore }}</h3>
              <p class="m-0 text-gray-500 text-xs">{{ messages.clickDownload }}</p>
            </div>
          </div>
          <div class="h-px bg-gray-100 my-0.5"></div>
          <div class="flex items-center py-2 gap-2">
            <div class="w-7 h-7 flex items-center justify-center text-xl">
              <Android class="text-[#000] text-2xl" />
            </div>
            <div class="flex flex-col">
              <h3 class="m-0 text-sm">{{ messages.android }}</h3>
              <p class="m-0 text-gray-500 text-xs">{{ messages.clickDownload }}</p>
            </div>
          </div>
          <div class="flex justify-center py-2">
            <!-- 二维码图片 - 占位，用户会手动替换 -->
            <img src="@/views/login/assets/qrcode.png" alt="QR Code" class="w-[120px] h-[120px]" />
          </div>
        </div>
      </el-popover>
    </div>

    <div class="w-full h-full flex">
      <!-- 左侧图片 -->
      <div class="flex-3 bg-white p-5 flex items-center justify-center">
        <div class="w-full h-full relative">
          <!-- <img
            src="@/views/login/assets/login-bg.png"
            alt="Login Background"
            class="w-full h-full object-cover rounded"
          /> -->
          <video src="@/views/login/assets/1.mp4" autoplay muted loop
            class="h-full w-full object-cover rounded-3xl video-bg"></video>

          <!-- Logo in top-left corner -->
          <div class="absolute top-6 left-6 z-10">
            <img src="@/views/login/assets/logo.png" alt="Logo" class="h-6 w-auto" />
          </div>
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="flex-2 h-full flex flex-col items-center justify-center bg-white relative py-10">
        <div class="w-4/5 flex flex-1 flex-col gap-10 justify-center">
          <h1 class="text-4xl text-gray-800 mb-10">
            {{ messages.title }}
          </h1>

          <div class="">
            <label class="block mb-2 text-base font-light! text-gray-800">{{ messages.email }}</label>
            <el-input v-model="loginForm.email" size="large" :placeholder="messages.emailPlaceholder"
              @input="clearError">
              <!-- 自定义后缀插槽，只在有内容时显示清空按钮 -->
              <template #suffix>
                <el-icon v-if="loginForm.email" class="input-action-btn" @click="loginForm.email = ''">
                  <Close />
                </el-icon>
              </template>
            </el-input>
          </div>

          <div class="">
            <label class="block mb-2 text-base font-light! text-gray-800">{{ messages.password }}</label>
            <el-input v-model="loginForm.password" size="large" :type="passwordVisible ? 'text' : 'password'"
              :placeholder="messages.passwordPlaceholder" @input="clearError">
              <!-- 自定义后缀插槽，调换按钮顺序 -->
              <template #suffix>
                <div class="flex items-center gap-1">
                  <!-- 显示/隐藏密码按钮 -->
                  <el-icon v-if="loginForm.password" class="input-action-btn"
                    @click="passwordVisible = !passwordVisible">
                    <View v-if="passwordVisible" />
                    <Hide v-else />
                  </el-icon>
                  <!-- 清空按钮 - 有内容时始终显示 -->
                  <el-icon v-if="loginForm.password" class="input-action-btn" @click="loginForm.password = ''">
                    <Close />
                  </el-icon>
                </div>
              </template>
            </el-input>
          </div>

          <div class="flex justify-between mb-6">
            <a href="javascript:;" class="!text-[#107082] text-sm no-underline" @click="showNoCompanyAccountDialog">{{
              messages.noCompanyAccount }}</a>
            <a href="javascript:;" class="!text-[#107082] text-sm no-underline" @click="showForgetPasswordDialog">{{
              messages.forgetPassword }}</a>
          </div>

          <!-- 错误信息显示区域 - 固定占位 -->
          <div class="error-message-container mb-4">
            <p v-if="loginError" class="text-red-500 text-sm text-left">{{ loginError }}</p>
          </div>

          <el-button type="primary" class="w-full h-[45px] text-base bg-teal-700" @click="handleLogin"
            :loading="loading" :disabled="loginDisabled">{{ messages.login }}</el-button>
        </div>

        <div class="flex flex-col gap-2 items-center text-gray-400 text-xs">
          <p class="flex gap-1">
            <span>{{ messages.copyright }}</span>
            <span>|</span>
            <span>{{ messages.userManual }}</span>
          </p>
          <p>{{ messages.copyrightText }}</p>
        </div>
      </div>
    </div>

    <!-- 忘记密码弹窗 -->
    <el-dialog v-model="forgetPasswordDialogVisible" width="400px" align-center>
      <template #header>
        <div class="flex items-center gap-2">
          <el-icon>
            <warning class="text-amber-400 text-2xl" />
          </el-icon>
          <span>{{ messages.forgetPasswordTitle }}</span>
        </div>
      </template>
      <div>
        <p>{{ messages.forgetPasswordContent }}</p>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button type="primary" @click="forgetPasswordDialogVisible = false">{{ messages.ok }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 无公司账号弹窗 -->
    <el-dialog v-model="noCompanyAccountDialogVisible" width="400px" align-center>
      <template #header>
        <div class="flex items-center gap-2">
          <el-icon>
            <warning class="text-amber-400 text-2xl" />
          </el-icon>
          <span>{{ messages.noCompanyAccountTitle }}</span>
        </div>
      </template>
      <div>
        <p>{{ messages.noCompanyAccountContent1 }}</p>
        <p>{{ messages.noCompanyAccountContent2 }}</p>
        <p><strong>{{ messages.emailContact }}</strong></p>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button type="primary" @click="noCompanyAccountDialogVisible = false">{{ messages.ok }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 会话过期弹窗 -->
    <SessionExpiredDialog v-model:visible="sessionExpiredVisible" :messages="messages as any" />

    <!-- 会话警告弹窗 -->
    <SessionWarningDialog v-model:visible="sessionWarningVisible" :messages="messages as any"
      @extend="handleSessionExtend" @logout="handleSessionLogout" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
// import { useUserStoreHook } from "@/store/modules/user";
// import { initRouter, getTopMenu } from "@/router/utils";
// import { message } from "@/utils/message";
import IOS from "~icons/ic/baseline-apple";
import Android from "~icons/uil/android";
import { Warning, View, Hide, Close } from "@element-plus/icons-vue";
import { useI18n } from "@/composables/useI18n";
import { logger } from "@/utils/logger";
import LanguageSelector from "@/components/i18n/LanguageSelector.vue";
import { sessionManager } from "@/utils/session";
import SessionExpiredDialog from "@/components/session/SessionExpiredDialog.vue";
import SessionWarningDialog from "@/components/session/SessionWarningDialog.vue";

import baseService from "@/service/baseService";
import { setCache } from "@/utils/cache";
import { CacheToken } from "@/constants/cacheKey";
import { useAppStore } from "@/store";

const router = useRouter();
const store = useAppStore();

// 使用多语言组合式函数
const { currentLanguage, messages, setLanguage } = useI18n();

// 密码可见性
const passwordVisible = ref(false);

// 弹窗控制
const forgetPasswordDialogVisible = ref(false);
const noCompanyAccountDialogVisible = ref(false);

// 会话管理弹窗控制
const sessionExpiredVisible = ref(false);
const sessionWarningVisible = ref(false);

// 忘记密码弹窗
const showForgetPasswordDialog = () => {
  forgetPasswordDialogVisible.value = true;
};

// 无公司账号弹窗
const showNoCompanyAccountDialog = () => {
  noCompanyAccountDialogVisible.value = true;
};

// 会话管理处理函数
const handleSessionExtend = () => {
  sessionManager.refreshSession();
  sessionWarningVisible.value = false;
};

const handleSessionLogout = () => {
  sessionManager.clearSession();
  sessionWarningVisible.value = false;
  router.push('/login');
};

// 清除错误信息
const clearError = () => {
  loginError.value = "";
};

// 登录按钮禁用：当邮箱或密码为空时禁用
const loginDisabled = computed(() => !loginForm.value.email || !loginForm.value.password || loading.value);
// 是否加载中
const loading = ref(false);
// 登录错误信息
const loginError = ref("");

const loginForm = ref({
  email: "",
  password: ""
});

const handleLogin = () => {
  // 清除之前的错误信息
  loginError.value = "";

  if (loginDisabled.value) return;

  loading.value = true;

  // 调用后端登录API
  baseService
    .post("/login", {
      email: loginForm.value.email,
      password: loginForm.value.password
    })
    .then((res: any) => {
      loading.value = false;
      if (res.code === 0) {
        // 存储token
        setCache(CacheToken, res.data, true);

        // 先拉取用户与菜单信息，随后跳转到“第一个可访问的菜单页”
        store.initApp().then(() => {
          // 计算第一个可访问菜单（优先内部页面）
          const findFirstPath = (menus: any[]): string | null => {
            for (const m of menus || []) {
              if (m.url && /^\//.test(m.url)) return m.url;
              if (m.children && m.children.length) {
                const p = findFirstPath(m.children);
                if (p) return p;
              }
            }
            return null;
          };
          const first = findFirstPath(store.state.menus) || "/error";
          // 初始化会话管理
          sessionManager.setLoginTime();
          sessionManager.setTimeout(1); // 改为1分钟，便于测试
          router.replace(first);
        }).catch(() => {
          // 兜底：初始化失败仍进入错误页
          sessionManager.setLoginTime();
          sessionManager.setTimeout(1); // 改为1分钟，便于测试
          router.replace("/error");
        });
      } else {
        // 统一显示错误信息，不管是什么类型的错误
        loginError.value = "Account does not exist or the password is incorrect.";
      }
    })
    .catch((error: any) => {
      loading.value = false;
      logger.error("登录错误:", error);

      // 统一显示错误信息，不管是什么类型的错误
      loginError.value = "Account does not exist or the password is incorrect.";
    });
};

// 监听回车键触发登录
const handleKeydown = (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    handleLogin();
  }
};

onMounted(() => {
  window.addEventListener('keydown', handleKeydown);
});

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown);
});
</script>

<style lang="scss" scoped>
/* Tailwind CSS已应用，这里不需要自定义样式 */
/* 由于flex-3和flex-2不是tailwind默认的类名，所以需要在tailwind配置中扩展 */
.flex-2 {
  flex: 2;
}

.flex-3 {
  flex: 3;
}



:deep(.el-input__wrapper) {
  background-color: #fafafa;
}

/* 输入框操作按钮样式 */
.input-action-btn {
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  color: #909399;
  font-size: 16px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  aspect-ratio: 1/1;
}

.input-action-btn:hover {
  color: #606266;
}

.input-action-btn:active {
  transform: scale(0.95);
}

.video-bg {
  position: relative;
}

/* 错误信息容器样式 - 固定占位 */
.error-message-container {
  min-height: 20px;
  /* 设置最小高度，确保有足够的空间显示错误信息 */
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
}

.error-message-container p {
  margin: 0;
  line-height: 1.4;
  word-wrap: break-word;
  max-width: 100%;
}
</style>
